package cc.iotkit.plugins.tcp.parser;

import io.vertx.core.buffer.Buffer;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;

import java.util.Map;

/**
 * 数据解码
 *
 * @author sjg
 */
@Slf4j
public class DataDecoder {
    private static short mid = 1;

    public static DataPackage decode(Buffer buffer) {
        log.info("receive tcp data: {}", buffer.toString());
        DataPackage data = new DataPackage();
        buffer.appendString("}}");
        Map<String, Object> map = JSON.parseObject(buffer.toString(), Map.class);
        data.setAddr( map.keySet().iterator().next());
        data.setCode((short)48);
        data.setMid(mid++);
        data.setPayloadMap(map);
        return data;
    }

    public static DataPackage decode1(Buffer buffer) {
        DataPackage data = new DataPackage();
        data.setAddr(buffer.getBuffer(0, 6).toString());
        data.setCode(buffer.getShort(6));
        data.setMid(buffer.getShort(8));
        data.setPayload(buffer.getBytes(10, buffer.length()));
        return data;
    }

}
